package com.time.oss.adpater;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.ListObjectsRequest;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.OSSObjectSummary;
import com.time.oss.entity.FileInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 阿里云 OSS 存储服务实现
 */
@Component
@RefreshScope
public class AliStorageAdapter implements StorageAdapter {

    @Resource
    private OSS ossClient;

    @Value("${aliyun.oss.autoCreateBucket:true}")
    private boolean autoCreateBucket;

    @Value("${aliyun.oss.domain:}")
    private String customDomain;

    @Value("${aliyun.oss.url-expire-seconds:3600}")
    private long urlExpireSeconds;

    private void ensureBucket(String bucketName) {
        boolean exists = ossClient.doesBucketExist(bucketName);
        if (!exists) {
            if (autoCreateBucket) {
                ossClient.createBucket(bucketName);
            } else {
                throw new IllegalArgumentException("Bucket 不存在且禁止自动创建: " + bucketName);
            }
        }
    }

    @Override
    public void createBucket(String bucketName) {
        ensureBucket(bucketName);
    }

    @Override
    public void uploadFile(MultipartFile uploadFile, String bucketName, String objectName) {
        try {
            ensureBucket(bucketName);
            String key = buildObjectKey(uploadFile, objectName);
            ossClient.putObject(bucketName, key, uploadFile.getInputStream());
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败", e);
        }
    }

    @Override
    public List<String> getAllBucket() {
        List<Bucket> buckets = ossClient.listBuckets();
        return buckets.stream().map(Bucket::getName).collect(Collectors.toList());
    }

    @Override
    public List<FileInfo> getAllFile(String bucketName) {
        ensureBucket(bucketName);
        List<FileInfo> files = new ArrayList<>();
        String nextMarker = null;
        boolean hasMore;
        do {
            ListObjectsRequest request = new ListObjectsRequest(bucketName).withMarker(nextMarker);
            ObjectListing listing = ossClient.listObjects(request);
            for (OSSObjectSummary summary : listing.getObjectSummaries()) {
                FileInfo fileInfo = new FileInfo();
                fileInfo.setFileName(summary.getKey());
                fileInfo.setDirectoryFlag(summary.getKey().endsWith("/"));
                fileInfo.setEtag(summary.getETag());
                files.add(fileInfo);
            }
            nextMarker = listing.getNextMarker();
            hasMore = listing.isTruncated();
        } while (hasMore);
        return files;
    }

    @Override
    public InputStream downloadFile(String bucketName, String objectName) {
        ensureBucket(bucketName);
        OSSObject object = ossClient.getObject(bucketName, objectName);
        return object.getObjectContent();
    }

    @Override
    public void deleteBucket(String bucketName) {
        try {
            ossClient.deleteBucket(bucketName);
        } catch (OSSException e) {
            throw new RuntimeException("删除桶失败: " + bucketName, e);
        }
    }

    @Override
    public void deleteBucket(String bucketName, String objectName) {
        ossClient.deleteObject(bucketName, objectName);
    }

    @Override
    public String getUrl(String bucketName, String objectName) {
        if (StringUtils.hasText(customDomain)) {
            return formatUrl(customDomain, objectName);
        }
        Date expiration = new Date(System.currentTimeMillis() + urlExpireSeconds * 1000L);
        URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
        return url.toString();
    }

    private String buildObjectKey(MultipartFile uploadFile, String objectName) {
        String filename = uploadFile.getOriginalFilename();
        if (!StringUtils.hasText(filename)) {
            filename = uploadFile.getName();
        }
        if (!StringUtils.hasText(objectName)) {
            return filename;
        }
        return objectName.endsWith("/") ? objectName + filename : objectName + "/" + filename;
    }

    private String formatUrl(String domain, String objectName) {
        String normalizedDomain = domain.endsWith("/") ? domain.substring(0, domain.length() - 1) : domain;
        String normalizedObject = objectName.startsWith("/") ? objectName.substring(1) : objectName;
        return normalizedDomain + "/" + normalizedObject;
    }
}
